<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h1>智能空气质检仪</h1>
        <h2>管理系统</h2>
        <div class="company">智慧环境技术有限公司</div>
      </div>
      <div class="login-form">
        <el-form ref="formRef" :model="loginForm" :rules="loginRules" label-position="top">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入用户名">
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input 
              v-model="loginForm.password" 
              type="password" 
              placeholder="请输入密码"
              @keyup.enter="handleLogin"
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="loading" class="login-button" @click="handleLogin">
              登录系统
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, reactive, ref } from 'vue';
import { User, Lock } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { login } from '../api/user'; // 导入登录API

export default defineComponent({
  components: { User, Lock },
  name: 'LoginView',
  setup() {
    const router = useRouter();
    
    // 组件初始化时清除所有登录状态
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    sessionStorage.clear(); // 清除会话存储
    
    const loginForm = reactive({
      username: '',
      password: '',
      rememberMe: false
    });

    const loginRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' }
      ]
    };

    const loading = ref(false);
    const formRef = ref(null);

    const handleLogin = () => {
      if (formRef.value) {
        formRef.value.validate((valid) => {
          if (valid) {
            loading.value = true;
            login({ username: loginForm.username, password: loginForm.password })
              .then(response => {
                console.log('登录响应:', response);
                if (response.code === 200 && response.data && response.data.token) {
                  // 存储标准格式的Bearer token
                  localStorage.setItem('token', `Bearer ${response.data.token}`);
                  
                  // 存储用户信息
                  if (response.data.userInfo) {
                    localStorage.setItem('userInfo', JSON.stringify(response.data.userInfo));
                  } else if (response.data.user) {
                    localStorage.setItem('userInfo', JSON.stringify(response.data.user));
                  }
                  
                  // 存储token过期时间
                  if (response.data.expiresIn) {
                    const expiresAt = Date.now() + (response.data.expiresIn * 1000);
                    localStorage.setItem('tokenExpires', expiresAt);
                  }
                  
                  ElMessage.success('登录成功，正在跳转...');
                  router.push('/dashboard');
                } else {
                  ElMessage.error(response.message || '登录失败，请检查用户名和密码');
                }
              loading.value = false;
              })
              .catch(error => {
                ElMessage.error(error?.message || '登录失败，请检查用户名和密码');
                loading.value = false;
            });
          } else {
            return false;
          }
        });
      }
    };

    return {
      loginForm,
      loginRules,
      loading,
      formRef,
      handleLogin
    };
  }
});
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #43cea2 0%, #185a9d 100%);
}

.login-box {
  width: 400px;
  padding: 30px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h1 {
  color: #409EFF;
  font-weight: 600;
  margin-bottom: 5px;
  font-size: 28px;
}

.login-header h2 {
  color: #409EFF;
  font-weight: 600;
  margin-bottom: 10px;
  font-size: 22px;
}

.login-header .company {
  color: #888;
  font-size: 14px;
}

.login-button {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
